/*
编写 : Hexh
时间 : 2012-6-13 14:11:39
*/
using System;
using System.ComponentModel;
using System.Web.Mvc;
using FsCarInfo.Core.Entity;
using FsCarInfo.Facade;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Authority;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.MVC.CommonSupport;
using HMIS.MVC.ViewModel;
using Iesi.Collections.Generic;
using HMIS.Infrastructure.Facade;
using HMIS.Infrastructure.Core.Entities;

namespace HMIS.MVC.Controllers
{
	/// <summary>
	///	 the mvc class of FsCartransfer
	/// </summary>
	public class FsCartransferController : BaseController
	{

		private readonly IFsCartransferFacade FsCartransferFacade;
		private readonly IHospUserFacade HospUserFacade;
		private readonly IInfraApproveFacade InfraApproveFacade;

		public FsCartransferController(IFsCartransferFacade FsCartransferFacade, IHospUserFacade HospUserFacade, IInfraApproveFacade InfraApproveFacade)
		{
			this.FsCartransferFacade = FsCartransferFacade;
			this.HospUserFacade = HospUserFacade;
			this.InfraApproveFacade = InfraApproveFacade;
		}

		[Description("访问商品车调派单管理页面")]
		[ViewPage]
		public ActionResult FsCartransfer()
		{
			ViewData["Text"] = "My 访问商品车调派单管理页面";
			return View();
		}

		#region 调拨页面

		[Description("访问商品车调拨单-查询页面")]
		[ViewPage]
		public ActionResult ViewFsCarTransferQuery()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车调拨单-申请页面")]
		public ActionResult ViewFsCarTransferAdd()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车调拨单-审批页面")]
		public ActionResult ViewFsCarTransferAprove()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车调拨单-提出页面")]
		public ActionResult ViewFsCarTransferSend()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车调拨单-接收页面")]
		public ActionResult ViewFsCarTransferRecv()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车调拨单-入库页面")]
		public ActionResult ViewFsCarTransferStoreIn()
		{
			return View();
		}

		#endregion

		#region 临时派车页面

		[Description("访问商品车调拨单-查询页面")]
		[ViewPage]
		public ActionResult ViewFsCarExpQuery()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车派车单-申请页面")]
		public ActionResult ViewFsCarExpAdd()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车派车单-审批页面")]
		public ActionResult ViewFsCarExpAprove()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车派车单-提出页面")]
		public ActionResult ViewFsCarExpSend()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车派车单-接收页面")]
		public ActionResult ViewFsCarExpRecv()
		{
			return View();
		}

		[ViewPage]
		[Description("访问商品车派车单-入库页面")]
		public ActionResult ViewFsCarExpStoreIn()
		{
			return View();
		}

		#endregion

		[ExtResult]
		[Description("添加修改FsCartransfer信息")]
		public ActionResult SaveOrUpdate()
		{
			FsCartransfer entity;
			if (String.IsNullOrEmpty(Request["Id"]))
			{
				CurrentUser cUser = new CurrentUser();
				entity = new FsCartransfer
				{
					TransferType = Request["TransferType"],
					OperUserId = Request["OperUserId"],
					OutDeptId = cUser.UserInfo.DepartmentId,
					InDeptId = Request["InDeptId"],
					ExpOutTime = Convert.ToDateTime(Request["ExpOutTime"]),
					ExpArvTime = Convert.ToDateTime(Request["ExpArvTime"]),
					Reason = Request["Reason"],
					Description = Request["Description"],
					CreateUser = User.Identity.Name,
					State = FsCartransferState.Editing,
				};
			}
			else
			{
				// get the entity.
				entity = FsCartransferFacade.Get(Request["Id"]);
				// set new value..
				entity.TransferType = Request["TransferType"];
				entity.OperUserId = Request["OperUserId"];
				entity.InDeptId = Request["InDeptId"];
				entity.ExpOutTime = Convert.ToDateTime(Request["ExpOutTime"]);
				entity.ExpArvTime = Convert.ToDateTime(Request["ExpArvTime"]);
				entity.Reason = Request["Reason"];
				entity.Description = Request["Description"];
			}
			// TODO ..保存调拨车辆清单..
			/*
			string[] authusers = Request["AuthorizeUsers"].Split(',');
			for (int i = 0; i < authusers.Length; i++)
			{
				entity.AuthorizeUsers.Add(HospUserFacade.Load(authusers[i]));
			}
			*/
			// 保存信息
			FsCartransferFacade.SaveOrUpdate(entity);

			return this.JsonFormat(new ExtResult { success = true, id = entity.Id });
		}

		[ExtResult]
		[Description("删除FsCartransfer基本资料")]
		public ActionResult Delete()
		{
			FsCartransferFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("物理删除FsCartransfer基本资料")]
		public ActionResult PhysicsDelete()
		{
			FsCartransferFacade.PhysicsDelete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("商品车调派提交审批")]
		public ActionResult ToApproveProcess()
		{
			foreach (string id in Request["Ids"].Split(','))
			{
				FsCartransfer entity = FsCartransferFacade.Get(id);
				if (entity.State != FsCartransferState.Editing)
				{
					throw new ValidationException("错误:商品车调派单[" + entity.Id + "]的当前状态是[" + entity.State + "].");
				}
				InfraApprove appr = InfraApproveFacade.GetByDeptAndType(entity.OutDeptId, entity.TransferType);

				if (appr != null)
				{
					string smsContent = entity.ToSmsString();
					InfraApproveFacade.InitApproveLog(appr.Id, entity.Id, smsContent);
				}

				entity.State = FsCartransferState.Appling;
				FsCartransferFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("商品车调派审批")]
		public ActionResult Approve()
		{
			if (String.IsNullOrEmpty(Request["Id"]))
				throw new ArgumentNullException("审批步骤ID不能为空.");
			// 审批步骤信息
			InfraApproveLog appLogStep = InfraApproveFacade.GetApproveLogStepById(Request["Id"]);
			appLogStep.InputAprCode = Request["InputAprCode"];
			appLogStep.InputUserLName = Request["InputUserLName"];
			appLogStep.InputUserPwd = Request["InputUserPwd"];
			appLogStep.InputApprState = Request["InputApprState"];
			appLogStep.Description = Request["Description"];
			// 添加审批步骤并返回审批结果
			int step = InfraApproveFacade.ProcedureApprove(appLogStep);
			// 审批通过
			if (step == 0)
			{
				FsCartransfer entity = FsCartransferFacade.Load(appLogStep.ApproveItemId);
				entity.State = FsCartransferState.Agreed;
				FsCartransferFacade.SaveOrUpdate(entity);
			}
			else if (step < 0)
			{
				FsCartransfer entity = FsCartransferFacade.Load(appLogStep.ApproveItemId);
				entity.State = FsCartransferState.Refused;
				FsCartransferFacade.SaveOrUpdate(entity);
			}

			return this.JsonFormat(new ExtResult { success = true, msg = step.ToString() });
		}

		[ExtResult]
		[Description("商品车调出")]
		public ActionResult SendOut()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsCartransfer entity = FsCartransferFacade.Get(id);
				if (entity.State != FsCartransferState.Agreed)
				{
					throw new ValidationException("错误:商品车调派单[" + entity.Id + "]的当前状态是[" + entity.State + "].不能进行调出.");
				}
				entity.State = FsCartransferState.Processing;
				entity.OutDpuserId = cUser.UserInfo.Id;
				entity.ActOutTime = System.DateTime.Now;
				// 修改提出的车辆清单信息
				foreach (FsCartransferDetail cardetail in entity.Cars)
				{
					cardetail.State = "已提出";
					cardetail.Car.State = FsCarState.InTransfer;
				}
				FsCartransferFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("商品车调派回场抵达")]
		public ActionResult SendRecive()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsCartransfer entity = FsCartransferFacade.Get(id);
				if (entity.State != FsCartransferState.Processing)
				{
					throw new ValidationException("错误:商品车调派单[" + entity.Id + "]的当前状态是[" + entity.State + "].不能进行调入.");
				}
				entity.State = FsCartransferState.Returned;
				entity.InDpuserId = cUser.UserInfo.Id;
				entity.ActArvTime = System.DateTime.Now;
				// 修改提出的车辆清单信息
				foreach (FsCartransferDetail cardetail in entity.Cars)
				{
					cardetail.State = "已抵达";
					cardetail.Car.State = FsCarState.ToStore;
					cardetail.Car.DepartmentId = entity.InDeptId;
				}
				FsCartransferFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("商品车调派确认入库")]
		public ActionResult SendStoreIn()
		{
			CurrentUser cUser = new CurrentUser();
			foreach (string id in Request["Ids"].Split(','))
			{
				FsCartransfer entity = FsCartransferFacade.Get(id);
				if (entity.State != FsCartransferState.Returned)
				{
					throw new ValidationException("错误:商品车调派单[" + entity.Id + "]的当前状态是[" + entity.State + "].不能进行确认入库.");
				}
				entity.State = FsCartransferState.Stored;
				entity.InDpuserId = cUser.UserInfo.Id;
				// 修改提出的车辆清单信息
				foreach (FsCartransferDetail cardetail in entity.Cars)
				{
					cardetail.State = "已入库";
					cardetail.Car.State = FsCarState.InStore;
					cardetail.Car.DepartmentId = entity.InDeptId;
				}
				FsCartransferFacade.SaveOrUpdate(entity);
			}
			return this.JsonFormat(new ExtResult { success = true });
		}

		[Description("获取FsCartransfer清单")]
		public ActionResult GetPlist()
		{
			long total;
			CurrentUser CUser = new CurrentUser();
			var data = FsCartransferFacade.GetPlist(
				Request["state"],
				Request["type"],
				CUser.UserInfo.DepartmentId,
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			//TODO : 修改关联查询返回的类型
			return this.JsonFormat(
				new ExtGirdData<FsCartransfer> { total = total, data = data },
				new string[] { "OperUser", "OutDept", "OutDpuser", "InDept", "InDpuser" });
		}

		[Description("获取FsCartransfer信息")]
		public ActionResult GetById()
		{
			var entity = FsCartransferFacade.Get(Request["Id"]);
			return this.JsonFormat(
			   new ExtFormLoadData<FsCartransfer> { data = new FsCartransfer[] { entity } }, new string[] { "AuthorizeUsers" }
			   );
		}

		[ExtResult]
		[Description("判断FsCartransfer字段是否唯一")]
		public ActionResult IsFieldExist()
		{
			var result = FsCartransferFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });
		}
	}
}
